package com.lvmama.config.watcher;

import com.lvmama.config.factory.ZooKeeperClientFactory;
import com.lvmama.config.common.Constant;
import com.lvmama.config.common.ZooKeeperConfigProperties;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;

import java.io.IOException;

/**
 * Created by troy on 2016/8/29.
 * kouhongyu@163.com
 */
public class ZooKeeperCuratorWatcher implements CuratorWatcher {

    public void process(WatchedEvent watchedEvent) throws Exception {
        /**
         * 有较的path 和 监听开关为打开状态
         */
        if (watchedEvent.getPath() != null && Boolean.TRUE.equals(Constant.watcherEnabled)) {
            try {
                CuratorFramework curator = ZooKeeperClientFactory.getInstance(Constant.zookeeperConfigAddress, Constant.NAME_SPACE);

                byte[] data = curator.getData().usingWatcher(this).forPath(watchedEvent.getPath());

//                System.out.println("path  = " + watchedEvent.getPath());
//                System.out.println("bytes = " + new String(data));

                ZooKeeperConfigProperties.putProperties(watchedEvent.getPath(), data);
                ZooKeeperConfigProperties.resetBeanField(watchedEvent.getPath(), data);

            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (KeeperException e) {
                e.printStackTrace();
            }
        }

    }
}
